const API_URL = 'https://dengwominsu.zgdwms.com';

function getHeader() {
  let token = wx.getStorageSync('token') || '';
  let header = {
    'content-type': 'application/json'
  };
  if (token) {
    header['token'] = token;
  }
  return header;
}
function wxLogin(reject) {
  // 登录
  wx.login({
    success: res => {
      // 发送 res.code 到后台换取 openId, sessionKey, unionId
      if (res.code) {
        const data = {
          wxCode: res.code
        }
        Request('POST', `/api/sso/CUSTOMER/login`, data).then(res => {
          wx.setStorageSync('token', res.token);
          reject('登录状态失效')
        }).catch(err => {
          wx.showToast({
            title: err,
            icon: "none",
            duration: 1000
          })
        })
      }
    }
  })
};
function Request(method, url, data = {}) {
  let promise = new Promise(function (resolve, reject) {
    wx.request({
      url: API_URL + url,
      data: data,
      method: method,
      header: getHeader(),
      success: res => {
        res = res.data;
        switch (res.code) {
          case 200:
            resolve(res.data);
            break;
          case 203:
            wx.removeStorageSync('token');
            wxLogin(reject)
            break;
          default:
            reject(res.message || res.msg||'系统异常，请联系技术人员!')
        }
      },
      fail: res => {
        reject('系统异常，请联系技术人员!');
        console.log(res)
      }
    })
  });
  return promise
}


module.exports = {
  Request
}